package TCP.EchoServer;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 服务器 TcpEchoServer
 */
public class TcpEchoServer {

    private ServerSocket listenSocket = null;
    ExecutorService pool = Executors.newCachedThreadPool();

    public TcpEchoServer(int port) throws IOException {
        listenSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        // 先建立连接
        while (true){
            Socket socket = listenSocket.accept();
//            new Thread(() -> {
//                processClient(socket);
//            }).start();
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    processClient(socket);
                }
            });
        }
    }
    public void processClient(Socket socket){
        System.out.println("客户端" + socket.getInetAddress().toString() + ": " + socket.getPort() + "建立连接");
        try(InputStream inputStream = socket.getInputStream()) {
            try(OutputStream outputStream = socket.getOutputStream()){
                Scanner scanner = new Scanner(inputStream);
                while (true){
                    if (!scanner.hasNext()){
                        System.out.println("客户端" + socket.getInetAddress().toString() + ": " + socket.getPort() + "断开连接");
                        break;
                    }
                    // 读取请求
                    String request = scanner.next();
                    // 得到响应
                    String response = process(request);
                    // 发送给客户
                    PrintWriter writer = new PrintWriter(outputStream);
                    writer.println(response);
                    // 刷新缓冲区
                    writer.flush();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }
}
